using System.Windows;
using System.Windows.Controls;

namespace ibba.src.sl.recursos.Validations
{
    public class TextBoxUpdateSourceService
    {
        public static bool GetUpdateBindingOnChanged(DependencyObject obj)
        {
            return (bool)obj.GetValue(UpdateBindingOnChangedProperty);
        }
        public static void SetUpdateBindingOnChanged(DependencyObject obj, bool value)
        {
            obj.SetValue(UpdateBindingOnChangedProperty, value);
        }

        // Using a DependencyProperty as the backing store for UpdateBindingOnChange.  This enables animation, styling, binding, etc...
        public static readonly DependencyProperty UpdateBindingOnChangedProperty =
            DependencyProperty.RegisterAttached("UpdateBindingOnChanged", typeof(bool), typeof(TextBoxUpdateSourceService),
                    new PropertyMetadata(new PropertyChangedCallback(UpdateBindingOnChangedPropertyCallback)));


        private static void UpdateBindingOnChangedPropertyCallback(DependencyObject sender, DependencyPropertyChangedEventArgs e)
        {
            TextBox textBox = sender as TextBox;

            textBox.TextChanged += new TextChangedEventHandler(textBox_TextChanged);
        }

        static void textBox_TextChanged(object sender, TextChangedEventArgs e)
        {
            TextBox txt = sender as TextBox;

            bool update = GetUpdateBindingOnChanged((DependencyObject)sender);

            if (update)
            {
                var bindingExpression = txt.GetBindingExpression(TextBox.TextProperty);
                if (bindingExpression != null)
                {
                    bindingExpression.UpdateSource();
                }
            }

        }
    }
}
